package services

import (
	"context"
	"database/sql"
	db "dhuviewer/db_query"
	"dhuviewer/dto"
	"fmt"

	"github.com/google/uuid"
	"github.com/labstack/gommon/log"
)

func CreateSocail(uid uuid.UUID, username string) error {
	res, err := queries.CreateSocail(context.Background(), db.CreateSocailParams{
		Uid:      uid,
		Username: sql.NullString{String: username, Valid: true},
		Level:    sql.NullString{String: "user", Valid: true},
		Honor:    sql.NullInt32{Int32: 0, Valid: true},
	})
	if err != nil {
		log.Info("error:", err)
		return err
	}
	fmt.Println(res)
	return nil
}

func GetSocail(uid uuid.UUID) (error, db.Socail) {
	socailData, err := queries.GetSocail(context.Background(), uid)
	if err != nil {
		log.Info("error:", err)
		return err, db.Socail{}
	}
	return err, socailData
}

func GetSocailWithSub(myid uuid.UUID, targetUid uuid.UUID) (error, db.Socail, bool) {
	socailData, err := queries.GetSocail(context.Background(), targetUid)
	if err != nil {
		log.Info("error:", err)
		return err, db.Socail{}, false
	}
	subList, err := queries.GetSubs(context.Background(), myid)
	if err != nil {
		log.Info("error:", err)
		return err, socailData, false
	}
	var subed bool = false
	for _, v := range subList.Sublist {
		if v.String() == targetUid.String() {
			subed = true
			break
		}
	}
	return err, socailData, subed
}

func UpdateSocailLevel(uid uuid.UUID, level string) error {
	err := queries.UpdateSocailLevel(context.Background(), db.UpdateSocailLevelParams{
		Uid:   uid,
		Level: sql.NullString{String: level, Valid: true},
	})
	return err
}

func UpdateSocailHonor(uid uuid.UUID, honor int32) error {
	err := queries.UpdateSocailHonor(context.Background(), db.UpdateSocailHonorParams{
		Uid:   uid,
		Honor: sql.NullInt32{Int32: honor, Valid: true},
	})
	return err
}

func UpdateUserSocail(uid uuid.UUID, tempSocail *dto.Socail) error {
	err := queries.UpdateUserSocail(context.Background(), db.UpdateUserSocailParams{
		Uid:      uuid.MustParse(tempSocail.Uid),
		Username: sql.NullString{String: tempSocail.Username, Valid: true},
		Tail:     sql.NullString{String: tempSocail.Tail, Valid: true},
		Tags:     tempSocail.Tags,
	})
	return err
}

func GetAllSocailData() ([]db.Socail, error) {
	res, err := queries.GetAllSocail(context.Background())
	if err != nil {
		log.Info("error:", err)
		return []db.Socail{}, err
	}
	return res, err
}
